﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "contact.h"
#include "SList.h"
//存储数据放入文本
void LoadContact(contact** con)
{
	FILE* pf = fopen("contact.txt", "rb");
	if (pf == NULL)
	{
		perror("fopen error!\n");
		return;
	}
	PeoInfo info;
	while (fread(&info, sizeof(info), 1, pf))
	{
		SLTPushBack(con, info);
	}
	printf("历史数据导入通讯录成功\n");
	fclose(pf);
	pf = NULL;
}

void InitContact(contact** con)
{
	LoadContact(con);//把本地的通讯录导入到链表
}
//添加数据
void AddContact(contact** con)
{
	PeoInfo info;
	printf("请输入姓名：\n");
	scanf("%s", &info.name);
	printf("请输入性别：\n");
	scanf("%s", &info.sex);
	printf("请输入年龄：\n");
	scanf("%d", &info.age);
	printf("请输入联系电话：\n");
	scanf("%s", &info.tel);
	printf("请输入地址：\n");
	scanf("%s", &info.addr);

	SLTPushBack(con, info);
	printf("插入成功!\n");
}


//查找
contact* FindByName(contact* con, char name[])
{
	SLTNode* cur = con;
	while (cur)
	{
		if (strcmp(cur->date.name,name) == 0)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
//删除通讯录数据
void DelContact(contact** con)//链表的删除指定位置的数据
{
	char name[NAME_MAX];
	printf("请输入要删除的用户名");
	scanf("%s", name);
	contact* pos = FindByName(*con, name);
	if (pos == NULL)
	{
		printf("删除的用户不存在，删除失败\n");
		return;
	}
	SLTErase(con, pos);
	printf("删除成功\n");
}



//展⽰通讯录数据
void ShowContact(contact** con)//链表的打印
{
	printf("%s %s %s %s %s\n", "姓名", "性别", "年龄", "电话", "地址");
	SLTNode* cur = con;
	while (cur)
	{
		printf("%3s %4s %4d %4s %4s\n",
			cur->date.name,
			cur->date.sex,
			cur->date.age,
			cur->date.tel,
			cur->date.addr);
		cur = cur->next;
	}
}
//查找通讯录数据
void FindContact(contact* con)
{
	char name[NAME_MAX];
	printf("请输入你需要查找的联系人姓名:");
	scanf("%s", name);
	SLTNode* pos = FindByName(con, name);
	if (pos == NULL)
	{
		printf("要查找的用户不存在，查找失败\n");
		return;
	}
	printf("查找成功\n");
	printf("%s %s %s %s %s\n", "姓名", "性别", "年龄", "电话", "地址");
	printf("%3s %4s %4d %4s %4s\n",
		pos->date.name,
		pos->date.sex,
		pos->date.age,
		pos->date.tel,
		pos->date.addr);
}
//修改通讯录数据
void ModifyContact(contact** con)
{
	char name[NAME_MAX];
	printf("请输入要修改的用户昵称：");
	scanf("%s", name);
	contact* pos = FindByName(*con, name);
	if (pos == NULL)
	{
		printf("要查找的用户不存在，修改失败\n");
		return;
	}
	printf("请输入要修改的姓名：\n");
	scanf("%s", pos->date.name);
	printf("请输入要修改的性别：\n");
	scanf("%s", pos->date.sex);
	printf("请输入要修改的年龄：\n");
	scanf("%d", &pos->date.age);
	printf("请输入要修改的联系电话：\n");
	scanf("%s", pos->date.tel);
	printf("请输入要修改的地址：\n");
	scanf("%s", pos->date.addr);
	printf("修改成功！\n");
}
void SaveContact(contact** con)
{
	FILE* pf = fopen("contact.txt", "wb");
	if (pf == NULL)
	{
		perror("fopen error!\n");
		return;
	}
	//将数据写入文件
	contact* cur = *con;
	while (cur)
	{
		fwrite(&(cur->date), sizeof(PeoInfo), 1, pf);
		cur = cur->next;
	}
	printf("通讯录数据保存成功\n");
}
//销毁通讯录数据
void DestroyContact(contact** con)
{
	SaveContact(con);
	SListDesTroy(con);
}